﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cofe.Core.Interfaces;
using Cofe.Core.Property;
using Cofe.Core.Utils;

namespace Cofe.Core.Implements
{
    [Export(typeof(ICofeService))]
    [ServicePriority(ServicePriorityAttribute.DefaultPriority_COFE)]
    public class ParseOnly : IPathParseBehaviorManager
    {
        #region Constructor

        public ParseOnly()
        {
        }

        #endregion

        #region Methods
       
        public virtual async Task<IPropertyHost> TryParsePathAsync(string fullParsePath, ParsableType type,
            EntryConstructionFlags flags = EntryConstructionFlags.Default)
        {
            if (type == ParsableType.ParsePathLookup)
                flags |= EntryConstructionFlags.LookupIfParseFailed;

            if (type == ParsableType.AutoDetect)
                type = PathUtils.DetectParseType(fullParsePath);
            
            foreach (var p in CofeServices.PathParserManager.PathParsers)
                if (p.SupportedParseType.HasFlag(type))
                {
                    var retVal = await p.TryParsePathAsync(fullParsePath, type, flags);
                    if (retVal != null)
                        return retVal;
                }
            return null;
        }      

        public virtual async Task<IPropertyHost> ParsePathAsync(string path, ParsableType type = ParsableType.AutoDetect, 
            EntryConstructionFlags flags = EntryConstructionFlags.Default)
        {
            var retVal = await TryParsePathAsync(path, type, flags);
            if (retVal == null) throw new System.IO.FileNotFoundException(path);
            else return retVal;
        }

        public virtual IPropertyHost TryParsePath(string path, ParsableType type = ParsableType.AutoDetect,
            EntryConstructionFlags flags = EntryConstructionFlags.Default)
        {
            return Task.Run<IPropertyHost>(async () => await TryParsePathAsync(path, type, flags)).Result;
        }

        public virtual IPropertyHost ParsePath(string path, ParsableType type = ParsableType.AutoDetect, EntryConstructionFlags flags = EntryConstructionFlags.Default)
        {
            return Task.Run<IPropertyHost>(async () => await ParsePathAsync(path, type, flags)).Result;
        }

        public virtual async Task<bool> ExistsAsync(string fullParsePath, ParsableType type)
        {
            foreach (var p in CofeServices.PathParserManager.PathParsers)
            {
                if (p.SupportedParseType.HasFlag(type) && await p.ExistsAsync(fullParsePath, type))
                    return true;
            }
            return false;
        }

        #endregion

        #region Data


        #endregion

        #region Public Properties
        

        #endregion

    }
}
